<template>
  <!-- 百度地图城市搜索组件 - 可复用的公共组件 -->
  <div class="map-container-wrapper">
    <div class="search-container">
      <input 
        v-model="searchCity" 
        type="text" 
        placeholder="请输入城市名称"
        @keyup.enter="searchByCity"
        class="search-input"
      />
      <button type="button" @click="searchByCity" class="search-button">
        <i class="el-icon-search"></i> 搜索
      </button>
    </div>
    <!-- 根据showMap属性决定是否显示地图 -->
    <div 
      id="map-container" 
      :class="{ hidden: !showMap }"
      class="map-content"
    ></div>
    <!-- 地图加载中状态 -->
    <div v-if="loading" class="loading-indicator">
      <div class="loading-spinner"></div>
      <span>地图加载中...</span>
    </div>
    <!-- 地图加载错误状态 -->
    <div v-else-if="mapLoadError" class="error-message">
      <i class="el-icon-error"></i>
      <span>地图加载失败，请检查网络连接</span>
    </div>
    <!-- 地图状态信息 -->
    <div v-else-if="currentCityInfo" class="map-status">
      <i class="el-icon-location"></i>
      <span>{{ currentCityInfo }}</span>
    </div>
  </div>
</template>

<script>
// 百度地图城市搜索公共组件
export default {
  name: 'MapContainer',
  // 定义组件可接收的属性
  props: {
    // 是否显示地图，默认为true
    showMap: {
      type: Boolean,
      default: true
    },
    // 默认搜索的城市
    defaultCity: {
      type: String,
      default: ''
    }
  },
  data() {
    return {
      loading: true,
      map: null,
      mapLoadError: false,
      searchCity: '',
      currentCityInfo: '',
      mapScript: null, // 保存地图脚本引用
      loadTimeout: null // 保存超时定时器ID
    };
  },
  watch: {
    // 监听默认城市变化
    defaultCity: {
      handler(newCity) {
        if (newCity && !this.searchCity) {
          this.searchCity = newCity;
          // 如果地图已加载完成，则自动搜索
          if (!this.loading && this.map) {
            this.searchByCity();
          }
        }
      },
      immediate: true
    }
  },
  mounted() {
    console.log('MapContainer组件挂载');
    // 立即设置地图容器尺寸
    const container = document.getElementById('map-container');
    if (container) {
      container.style.width = '100%';
      container.style.height = '350px'; // 减小高度，优化弹出层显示
      container.style.position = 'relative';
      console.log('地图容器尺寸设置完成:', container.offsetWidth, container.offsetHeight);
    }
    
    // 调用百度地图官方推荐的加载方式
    this.loadBaiduMap();
  },
  
  // 组件销毁时清理地图资源
  beforeDestroy() {
    console.log('MapContainer组件销毁，开始清理地图资源');
    
    // 清理超时定时器
    if (this.loadTimeout) {
      clearTimeout(this.loadTimeout);
      this.loadTimeout = null;
      console.log('超时定时器清理成功');
    }
    
    // 清理地图实例
    if (this.map && this.map.destroy) {
      try {
        this.map.destroy();
        console.log('地图实例销毁成功');
      } catch (error) {
        console.error('销毁地图实例时出错:', error);
      }
      this.map = null;
    }
    
    // 清理全局变量
    if (window.mapInit) {
      delete window.mapInit;
    }
    
    // 移除特定的地图脚本引用
    if (this.mapScript && this.mapScript.parentNode) {
      try {
        this.mapScript.parentNode.removeChild(this.mapScript);
        console.log('移除特定地图脚本成功');
      } catch (error) {
        console.error('移除特定地图脚本时出错:', error);
      }
      this.mapScript = null;
    }
    
    // 移除可能存在的其他地图脚本
    const mapScripts = document.querySelectorAll('script[src*="api.map.baidu.com"]');
    mapScripts.forEach(script => {
      try {
        script.remove();
        console.log('移除地图脚本:', script.src);
      } catch (error) {
        console.error('移除地图脚本时出错:', error);
      }
    });
    
    console.log('地图资源清理完成');
  },
  methods: {
    // 百度地图加载函数 - 改进版，使用https并避免document.write问题
    loadBaiduMap() {
      console.log('开始加载百度地图API');
      
      // 百度地图官方推荐的全局变量设置
      window.BMAP_PROTOCOL = "https";
      window.BMapGL_loadScriptTime = (new Date).getTime();
      
      // 全局初始化函数
      window.mapInit = () => {
        console.log('百度地图API回调触发');
        this.initializeMap();
      };
      
      // 检查是否已经加载过百度地图API
      if (window.BMapGL) {
        console.log('百度地图API已加载，直接初始化地图');
        this.initializeMap();
        return;
      }
      
      // 使用HTTPS协议加载地图API，避免document.write警告
      const scriptNode = document.createElement("script");
      scriptNode.type = "text/javascript";
      scriptNode.src = "https://api.map.baidu.com/api?v=1.0&type=webgl&ak=WwSE3jrPpTgqnvvmjeoNvlmJsXUYFQ2X&callback=mapInit";
      scriptNode.async = true; // 异步加载
      scriptNode.defer = true; // 延迟执行
      
      // 错误处理
      scriptNode.onerror = () => {
        console.error('百度地图API加载失败');
        this.loading = false;
        this.mapLoadError = true;
      };
      
      // 添加到文档头部
      document.head.appendChild(scriptNode);
      console.log('百度地图脚本添加到文档头部');
      
      // 保存脚本引用以便后续清理
      this.mapScript = scriptNode;
      
      // 添加超时处理
      this.loadTimeout = setTimeout(() => {
        if (this.loading && !window.BMapGL) {
          console.error('百度地图API加载超时');
          this.loading = false;
          this.mapLoadError = true;
        }
      }, 10000);
    },
    
    // 地图初始化函数
    initializeMap() {
      console.log('开始初始化地图');
      
      // 再次检查BMapGL
      if (!window.BMapGL) {
        console.error('BMapGL对象未定义');
        this.loading = false;
        this.mapLoadError = true;
        return;
      }
      
      console.log('BMapGL对象可用');
      
      try {
        // 获取地图容器
        const container = document.getElementById('map-container');
        console.log('地图容器:', container);
        console.log('地图容器尺寸:', container.offsetWidth, container.offsetHeight);
        
        // 创建地图实例
        console.log('创建地图实例');
        this.map = new window.BMapGL.Map("map-container");
        console.log('地图实例创建成功');
        
        // 设置中心点（北京坐标）
        const point = new window.BMapGL.Point(116.404, 39.915);
        console.log('设置地图中心点:', point);
        
        // 设置地图缩放级别
        this.map.centerAndZoom(point, 10);
        console.log('地图缩放级别设置完成');
        
        // 添加缩放控件
        this.map.enableScrollWheelZoom(true);
        console.log('启用滚轮缩放');
        
        // 添加一个简单的标记
        const marker = new window.BMapGL.Marker(point);
        this.map.addOverlay(marker);
        console.log('添加地图标记');
        
        this.loading = false;
        console.log('地图初始化完成');
      } catch (error) {
        console.error('地图初始化错误:', error);
        this.loading = false;
        this.mapLoadError = true;
      }
    },
    
    // 根据城市名称搜索并定位
    searchByCity() {
      if (!this.searchCity || !this.map || !window.BMapGL) {
        console.warn('搜索条件不满足');
        return;
      }
      
      console.log('开始搜索城市:', this.searchCity);
      
      // 创建地理编码实例
      const myGeo = new window.BMapGL.Geocoder();
      
      // 进行地理编码
      myGeo.getPoint(this.searchCity, (point) => {
        if (point) {
          console.log('获取到城市坐标:', point);
          
          // 定位到该城市
          this.map.centerAndZoom(point, 12);
          
          // 清除当前所有标记
          this.map.clearOverlays();
          
          // 添加新标记
          const marker = new window.BMapGL.Marker(point);
          this.map.addOverlay(marker);
          
          // 构建城市信息对象
          const cityData = {
            name: this.searchCity,
            longitude: point.lng,
            latitude: point.lat,
            formattedAddress: `${this.searchCity} - 经纬度: ${point.lng.toFixed(6)}, ${point.lat.toFixed(6)}`
          };
          
          // 更新当前城市信息
          this.currentCityInfo = cityData.formattedAddress;
          
          // 触发citySelected事件，将城市数据传递给父组件
          this.$emit('city-selected', cityData);
          console.log('触发city-selected事件:', cityData);
        } else {
          console.warn('未找到该城市:', this.searchCity);
          this.currentCityInfo = `未找到城市: ${this.searchCity}`;
          
          // 触发搜索失败事件
          this.$emit('search-error', {
            name: this.searchCity,
            error: '未找到该城市'
          });
        }
      }, this.searchCity); // 第三个参数是检索区域，一般设为城市名
    }
  }
};
</script>

<style scoped>
/* 地图容器主样式 */
.map-container-wrapper {
  width: 100%;
  height: 100%;
  position: relative;
  background-color: #ffffff;
  border-radius: 8px;
  overflow: hidden;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  display: flex;
  flex-direction: column;
}

/* 搜索容器样式 */
.search-container {
  padding: 15px;
  background-color: #f8f9fa;
  border-bottom: 1px solid #e9ecef;
  display: flex;
  gap: 12px;
  align-items: center;
}

/* 搜索输入框样式 */
.search-input {
  flex: 1;
  padding: 10px 15px;
  font-size: 14px;
  border: 2px solid #dcdfe6;
  border-radius: 6px;
  transition: all 0.3s ease;
  outline: none;
}

.search-input:focus {
  border-color: #409eff;
  box-shadow: 0 0 0 3px rgba(64, 158, 255, 0.1);
}

.search-input::placeholder {
  color: #c0c4cc;
}

/* 搜索按钮样式 */
.search-button {
  padding: 10px 20px;
  font-size: 14px;
  font-weight: 500;
  background-color: #409eff;
  color: white;
  border: none;
  border-radius: 6px;
  cursor: pointer;
  transition: all 0.3s ease;
  display: flex;
  align-items: center;
  gap: 6px;
}

.search-button:hover {
  background-color: #66b1ff;
  transform: translateY(-1px);
  box-shadow: 0 2px 8px rgba(64, 158, 255, 0.3);
}

.search-button:active {
  transform: translateY(0);
}

/* 地图内容区域 */
.map-content {
  flex: 1;
  width: 100%;
  background-color: #f5f5f5;
  position: relative;
  min-height: 0;
}

/* 隐藏地图样式 */
.map-content.hidden {
  display: none;
}

/* 加载指示器样式 */
.loading-indicator {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  background-color: rgba(255, 255, 255, 0.95);
  padding: 20px 30px;
  border-radius: 8px;
  z-index: 100;
  box-shadow: 0 4px 16px rgba(0, 0, 0, 0.15);
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 10px;
  animation: fadeIn 0.3s ease;
}

/* 加载动画 */
.loading-spinner {
  width: 30px;
  height: 30px;
  border: 3px solid #f3f3f3;
  border-top: 3px solid #409eff;
  border-radius: 50%;
  animation: spin 1s linear infinite;
}

@keyframes spin {
  0% { transform: rotate(0deg); }
  100% { transform: rotate(360deg); }
}

@keyframes fadeIn {
  from { opacity: 0; transform: translate(-50%, -50%) scale(0.9); }
  to { opacity: 1; transform: translate(-50%, -50%) scale(1); }
}

/* 错误信息样式 */
.error-message {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  background-color: rgba(255, 255, 255, 0.95);
  padding: 20px 30px;
  border-radius: 8px;
  z-index: 100;
  box-shadow: 0 4px 16px rgba(0, 0, 0, 0.15);
  display: flex;
  align-items: center;
  gap: 10px;
  color: #f56c6c;
  animation: fadeIn 0.3s ease;
}

.error-message i {
  font-size: 20px;
}

/* 地图状态信息样式 */
.map-status {
  position: absolute;
  bottom: 15px;
  left: 15px;
  background-color: rgba(255, 255, 255, 0.95);
  padding: 10px 15px;
  border-radius: 6px;
  z-index: 100;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
  display: flex;
  align-items: center;
  gap: 8px;
  font-size: 14px;
  color: #606266;
  animation: slideUp 0.3s ease;
}

@keyframes slideUp {
  from { opacity: 0; transform: translateY(20px); }
  to { opacity: 1; transform: translateY(0); }
}

.map-status i {
  color: #409eff;
  font-size: 16px;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .search-container {
    padding: 10px;
    flex-direction: column;
  }
  
  .search-input {
    width: 100%;
  }
  
  .search-button {
    width: 100%;
    justify-content: center;
  }
  
  .loading-indicator,
  .error-message {
    padding: 15px 20px;
    margin: 0 20px;
    width: calc(100% - 40px);
    box-sizing: border-box;
  }
  
  .map-status {
    bottom: 10px;
    left: 10px;
    right: 10px;
    font-size: 12px;
  }
}
</style>